<template>
	<view class="page">
		<view class="top_img">
			<image style="width: 500rpx;height: 80rpx;" src="https://beihai-food.oss-cn-beijing.aliyuncs.com/04.png">
			</image>
			<view class="f14" style="color: #fff;margin-top: 16rpx;">
				每周二12:00至周五12:00开放
			</view>

		</view>
		<view class="content">
			<calendar :weekIndex="weekIndex" :mainData="foodDateType" @cutWeek="cutWeek"></calendar>
			<view class="flex_between">
				<view class="flex_align_conter" >
					<button style="font-size: 30rpx;" class="login-btn cu-btn block bg-green-plain round" @click="copyPerDiem" v-if="weekNewType != 2">按日复制</button>
					<button  class="login-btn cu-btn block bg-green-plain round" @click="copyByWeek"
						style="margin-left: 20rpx;font-size: 30rpx;" v-if="weekNewType != 2">按周复制</button>
				</view>
				<button style="font-size: 30rpx;" class="login-btn cu-btn block bg-green-plain  round" @click="recommen">智能推荐</button>
			</view>
			<view class="tabs">
				<u-tabs :activeStyle="{ 'color': '#0EB275','fontSize':'36rpx' }"  :inactiveStyle="{'fontSize':'36rpx'}" :itemStyle="{'height': '80rpx' }" lineColor="#0EB275"
					lineWidth="28" :list="tabsList" @click="tabsClick" :current="tabsCurrent"></u-tabs>
			</view>
			<view class="flex meal_main">
				<view class="tabsSide h100">
				<!-- 	<view class="t"  @click="tabsSideCilck1(0)">
						<view :class="{'t_active': tabsSideIndex==0}">
							套餐
						</view>
					</view>
					<view class="t"  @click="tabsSideCilck2(1)">
						<view :class="{'t_active': tabsSideIndex==1}">
							菜品
						</view>
					</view> -->
					<view class="t" v-for="(item,index) in tabsSide" @click="tabsSideCilck(index)">
						<view style="font-size: 36rpx;" :class="{'t_active':index == tabsSideIndex}">
							{{item}}
						</view>
					</view>
				</view>
				<view class="flex1">
					<view class="right_side">
						<!--  -->
						<setMealReservation :tabsSideIndex="tabsSideIndex" :packageList="packageList" v-for="item in packageList" :item="item"
							@updateNum="handleUpdateNum" @comboDetails="comboDetails">
						</setMealReservation>
					</view>
				</view>

			</view>
			<view class="">
				<shoppingBag :cartList="selectedPackages" @undateData="undateShoppingData" :weekNewType="weekNewType"></shoppingBag>
			</view>
			<uni-popup ref="comboPopup" type="bottom" class="">
				<comboDetailsView ref="comboDetailsView" v-if="comboId" @closePopup="closePopup" :comboId="comboId"
					@addShopping="addShopping" :date="weekObj.fullDate || foodDateType[0].date"/>
			</uni-popup>
		</view>
		<navigationBar tabbarIndex="1"></navigationBar>
	</view>
</template>
<script>
	import {
		listData,
		getData,
		delData,
		addData,
		updateData
	} from "@/api/system/dict/data"

	import {
		mapState,
		mapMutations
	} from 'vuex';
	import navigationBar from '@/components/common/navigationBar.vue'
	import calendar from '@/components/common/calendar.vue'
	import setMealReservation from '@/components/common/setMealReservation.vue'
	import shoppingBag from '@/components/common/shoppingBag.vue'
	import comboDetailsView from '@/components/common/comboDetailsView.vue'
	
	import {
		getfoodSetMealAPI,
		getfoodSetMealAPI2,
		getfoodDateTypeAPI,
		getfoodDateTypeAPI2,
		getComboListAPI,
		getComboListAPI2,
		getDishListAPI,
		getDishListAPI2
	} from '@/api/index.js'

	import {
		getRangeCopyAPI
	} from "@/subpackages/user/api/index.js"
	// uni.hideTabBar()
	export default {
		name: '',
		components: {
			navigationBar,
			calendar,
			setMealReservation,
			shoppingBag,
			comboDetailsView
		},


		data() {
			return {
				maskShow:false,
				selectedComboData: {}, // 选中的套餐
				comboId: '',
				// paramsData: {
				// 	time: '7-21',
				// 	meals: '1',
				// 	state: '1'
				// },
				foodDateType: [],
				weekObj: {},
				shoppingData: [], // 总数据
				weekIndex: 0,
				tabsSide: ['套餐', '菜品'],
				tabsSideIndex: 0, // 侧面tabs
				tabsCurrent: 0, // 上面tabs
				// packageData: [], // 一天的数据
				mealsArray: [], //  meals
				packageList: [], // 具体的List
				tabsList: [],
				paramsDate: {},
				coubliShow: false,
				tableColumn: [],
				tableCuisine: [],
				weekNewType:0,

			}

		},
		// watch: {
		// 	weekIndex: {
		// 		handler(e) {
		// 		},
		// 	},
		// },
		computed: {
			...mapState({
				shoppingBagData: state => state.user.shoppingBagData
			}),
			selectedPackages() {
				// 存放 num > 0 的套餐
				return this.shoppingData.map(day => {
					const filteredDay = JSON.parse(JSON.stringify(day)) // 深拷贝避免污染原数据
					const meals = ['meals1', 'meals2', 'meals3']
					const lists = ['comboList', 'dishList']

					meals.forEach(mealKey => {
						lists.forEach(listKey => {
							if (
								filteredDay.dictDataList[mealKey] &&
								filteredDay.dictDataList[mealKey][listKey]
							) {
								filteredDay.dictDataList[mealKey][listKey] =
									filteredDay.dictDataList[mealKey][listKey].filter(
										item => Number(item.saleNum) > 0
									)
							}
						})
					})

					return filteredDay
				})
			}
		},
		onLoad(e) {
			if (e.type == 1) {
				this.paramsDate = e
			}
			if(e.type == 2){
				this.weekNewType = e.type
			}
			
			this.getShoppingData()
			this.dictData()

		},
		onShow() {
		console.log(this.$store.state.user.type)
		if(this.$store.state.user.type == 1){
			this.shoppingData = [];
			this.getShoppingData()
			this.dictData()
			this.maskShow = true;
		}
		console.log(123456)
			
		},
		created() {

		},
		methods: {
			tabsSideCilck(index){
				if(index == 0){
					this.tabsSideCilck1(index)
				}else{
					this.tabsSideCilck2(index)
				}
			},
			insertPropertyByDictLabel(arr, mapping) {
				// 深拷贝原数组，避免修改原数据
				return JSON.parse(JSON.stringify(arr)).map(item => {
					// 检查当前对象是否有dictLabel属性
					if (item && item.dictLabel !== undefined) {
						// 查找对应的映射关系
						const propertyMap = mapping[item.dictLabel];
						// 如果存在映射关系，则添加对应的属性
						if (propertyMap && typeof propertyMap === 'object') {
							return {
								...item,
								...propertyMap
							};
						}
					}
					// 如果没有匹配的映射关系，返回原对象
					return item;
				});
			},
			updateArr1ByDictLabelKey(arr1, arr, newValue = true) {
				// 深拷贝原数组，避免修改原始数据
				const newArr1 = JSON.parse(JSON.stringify(arr1));

				// 提取arr数组中所有的dictLabelKey值
				const labelKeys = arr
					.filter(item => item && item.dictLabelKey !== undefined)
					.map(item => item.dictLabelKey);

				// 遍历arr1数组中的每个对象
				newArr1.forEach(item => {
					// 检查每个dictLabelKey是否存在于当前对象中
					labelKeys.forEach(key => {
						if (item.hasOwnProperty(key)) {
							// 如果存在该属性，则更新其值
							item[key] = newValue;
						}
					});
				});

				return newArr1;
			},
			async dictData() {
				// 定义映射关系：key是dictLabel的值，value是要插入的属性键值对
				const labelMapping = {
					"菜品": {
						dictLabelKey: "isListItem",
					},
					"现售价": {
						dictLabelKey: "isPrice",
					},
					"原价": {
						dictLabelKey: "isOriginalPrice",
					}
				};
				// 调用函数
				const result = await listData({
					dictType: "combo_column",
					pageSize: 99,
					pageNum: 1
				})

				const data = await listData({
					dictType: "cuisine_column",
					pageSize: 99,
					pageNum: 1
				})
				const T = JSON.parse(JSON.stringify(result.rows));

				const S = JSON.parse(JSON.stringify(data.rows));
				this.tableColumn = this.insertPropertyByDictLabel(T.filter(item => item.dictValue == 1), labelMapping);
				this.tableCuisine = S.filter(item => item.dictValue == 1);
				const res = await listData({
					dictType: "food_type",
					pageSize: 99,
					pageNum: 1
				})

				this.tabsSide = res.rows.filter(el => el.status == 0).map(el => el.dictLabel)
			},
			getNextWeekSameDay(dateStr) {
				// 1. 目标星期几（0=周日 ... 6=周六）
				const targetDay = new Date(dateStr).getDay();

				// 2. 今天
				const today = new Date();
				const todayDay = today.getDay();

				// 3. 距离本周目标星期几的天数（可能为负）
				let delta = targetDay - todayDay;
				let deltas = targetDay - todayDay;
				return this.getNextWeekDay(targetDay == 0 ? 7 : targetDay)
			},
			getNextWeekDay(dayOfWeek) {
				if (dayOfWeek < 1 || dayOfWeek > 7) {
					throw new Error("请输入1-7的数字，1=周一，7=周日");
				}

				const today = new Date();
				const currentDay = today.getDay(); // 今天星期几（0=周日，1=周一，...6=周六）

				// 计算目标星期几与今天相差的天数
				let daysToAdd;
				if (dayOfWeek === 7) {
					// 如果输入7（周日），JavaScript的getDay()返回0
					daysToAdd = 7 - currentDay + 7; // 确保是下周
				} else {
					// 其他情况（1-6）计算差值，确保是下周
					daysToAdd = (7 - currentDay + dayOfWeek) % 7 + 7;
				}

				// 计算下周的日期
				const nextWeekDate = new Date(today);
				nextWeekDate.setDate(today.getDate() + daysToAdd);

				// 格式化为 YYYY-MM-DD
				const year = nextWeekDate.getFullYear();
				const month = String(nextWeekDate.getMonth() + 1).padStart(2, "0");
				const day = String(nextWeekDate.getDate()).padStart(2, "0");

				return `${year}-${month}-${day}`;
			},
			copyPerDiem() {
				this.$tab.navigateTo('/subpackages/user/pages/order/copyPerDiem')
			},
			copyByWeek() {
				this.$tab.navigateTo('/subpackages/user/pages/order/copyPerWeek')
			},
			// pages/order/copyPerDiem
			recommen() {
				this.packageList = this.packageList.sort((a, b) => b.sales - a.sales);
				let o = this.packageList[0]
				if (o.saleNum >= 1) return this.$modal.msg('您已选择推荐方案')
				if (o.limitPerUser != '-1' && o.saleNum >= Number(o.limitPerUser)) return this.$modal.msg('超出限购数量')
				const r = o.num - o.sales
				if (o.saleNum >= r) return this.$modal.msg('推荐方案库存不足')
				o.saleNum++
				this.persistenceShoppingBag()
			},
			addShopping() {
				if (this.selectedComboData.limitPerUser != '-1' && this.selectedComboData.saleNum >= Number(this
						.selectedComboData.limitPerUser))
					return this.$modal.msg('超出限购数量')
				const r = this.selectedComboData.num - this.selectedComboData.sales
				if (this.selectedComboData.saleNum >= r) return this.$modal.msg('库存不足')
				this.closePopup()
				this.handleUpdateNum(this.selectedComboData, this.selectedComboData.saleNum + 1)
			},
			closePopup() {
				// console.log('closePopup');
				this.$refs.comboPopup.close()
				this.comboId = null
			},
			comboDetails(e) {
				this.comboId = e.comboId
				this.selectedComboData = e
				// this.$refs.popup.open()
				this.$nextTick(() => {
					this.$refs.comboDetailsView.getComboDetail()
					this.$refs.comboDetailsView.tableColumn = e.tableColumn ? e.tableColumn : []
					this.$refs.comboDetailsView.tableCuisine = e.tableCuisine ? e.tableCuisine : []
					this.$refs.comboPopup.open()
				})

			},

			addIdsToItems(contentData) {
				// console.log(contentData);
				// return contentData.map(day => {
				const newDay = JSON.parse(JSON.stringify(contentData)); // 深拷贝
				newDay.forEach(item => {
					if (!item.lzy_id) { // 如果还没有 id，就生成一个
						item.lzy_id = this
							.generateUniqueId(); // 自定义生成唯一ID的方法
					}
				});
				return newDay;
				// });
			},

			// 生成唯一ID的方法（示例）
			generateUniqueId() {
				return 'id_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
			},
			// 使用示例
			async getfoodDateType() {
				let res;
				if(this.weekNewType == 2){
					res = await getfoodDateTypeAPI2()
				}else{
					res = await getfoodDateTypeAPI()
				}
				this.foodDateType = res.data
				const index = res.data.findIndex(item => item.orderType == 0)
				if (index === -1) {
					return this.$modal.msg('已经订过了')
				} else {
					this.weekIndex = index
					// this.weekObj = 
					this.weekObj = this.foodDateType[index]
				}

				this.getfoodSetMeal()

			},
			setTabsList(data) {
				const mealsMap = {
					meals1: {
						id: 1,
						name: '早餐'
					},
					meals2: {
						id: 2,
						name: '午餐'
					},
					meals3: {
						id: 3,
						name: '晚餐'
					},
				};

				const obj = data[0].dictDataList;

				this.tabsList = Object.keys(mealsMap)
					.filter(key => obj.hasOwnProperty(key))
					.map(key => mealsMap[key]);
			},
			cutWeek(e) {
				console.log(this.weekObj)
				this.weekIndex = e.index
				this.weekObj = e.day;
				this.tabsClick({
					index: this.tabsCurrent || 0
				})

			},
			tabsClick(e) {
				
				if (e) {
					this.tabsCurrent = e.index
				}
				console.log('上面切换了', e, this.tabsCurrent, )
				console.log('上面切换成查看左边', this.tabsSideIndex, e.index)
				if(this.tabsSideIndex==0){
					console.log('调用套餐', )
					this.tabsSideCilck1()
					return
				}
				if(this.tabsSideIndex==1){
					console.log('调用菜品', )
					this.tabsSideCilck2()
					return
				}
				// this.tabsSideCilck(this.tabsSideIndex)
			},
			// 左侧套餐点击事件
			tabsSideCilck1() {
				
				this.tabsSideIndex = 0
				console.log('左边切换了',this.tabsSideIndex,this.packageList)
				console.log('左边切换查看上面', this.tabsCurrent, this.tabsSide)
				// 第几天
				this.packageList = []; // 清空当前列表，避免残留数据

				const obj = this.tabsList[this.tabsCurrent]
				let d = {
					date: this.foodDateType[this.weekIndex].weekDay,
					type: obj.id,
				}
                 // 点击左侧的套餐
				// 套餐
				this.getComboList(d)
			},
			// 左侧菜品点击事件
			tabsSideCilck2() {
				
				this.tabsSideIndex = 1
				console.log('左边菜品点击切换了',this.tabsSideIndex, this.packageList)
				console.log('左边菜品点击切换查看上面', this.tabsCurrent, this.tabsSide)
			// 	// 第几天
				this.packageList = []; // 清空当前列表，避免残留数据
			
				const obj = this.tabsList[this.tabsCurrent]
				let d = {
					date: this.foodDateType[this.weekIndex].weekDay,
					type: obj.id,
				}
				// 点击左侧的菜品
				// 菜品
				this.getDishList(d)
			},
			async getComboList(d) {
				let dictDataList = this.shoppingData[this.weekIndex].dictDataList;
				let obj = this.tabsList[this.tabsCurrent];
				const mealsKey = `meals${obj.id}`;
				const property = 'comboList'; // 固定检查套餐列表

				// 1. 先检查是否有缓存数据
				if (dictDataList[mealsKey][property] && dictDataList[mealsKey][property].length > 0) {
					console.log('是否有缓存数据', this.shoppingData)
					this.packageList = dictDataList[mealsKey][property];
					return;
				}
				console.log('是否往下走了')

				// 2. 没有缓存数据则请求接口
				let res;
				if(this.weekNewType == 2){
					 res = await getComboListAPI2({
						...d,
						weyDate: this.weekObj.fullDate
					});
				}else{
					 res = await getComboListAPI({
						...d,
						weyDate: this.weekObj.fullDate
					});
				}
				
				if (res.data.length > 0) {
					res.data.forEach(item => {
						item.isListItem = false
						item.isPrice = false
						item.isOriginalPrice = false
					})
				}
				const newResult = this.updateArr1ByDictLabelKey(res.data, this.tableColumn, true)
				// 3. 处理返回数据
				if (res.data.length === 0 && !this.coubliShow) {
					// 如果套餐为空，并且当前是套餐标签（tabsSideIndex === 0）
					if (this.tabsSideIndex === 0) {
						// 检查菜品是否也为空
						const dishList = dictDataList[mealsKey]['dishList'] || [];
						if (dishList.length === 0) {
							// 如果菜品也为空，不自动切换（避免无限循环）
						} else {
							// 如果菜品不为空，切换到菜品
							this.tabsSideIndex = 1;
							this.getDishList(d);
						}
					}

					this.coubliShow = true;
				} else {
					// 正常处理套餐数据
					this.packageList = this.addIdsToItems(newResult);
					dictDataList[mealsKey][property] = this.packageList;
					this.persistenceShoppingBag();
				}
				console.log('调用是套餐', this.packageList)
			},
			async getDishList(d) {

				let dictDataList = this.shoppingData[this.weekIndex].dictDataList;
				// 确定 meals 键名
				let obj = this.tabsList[this.tabsCurrent]
				const mealsKey = `meals${obj.id}`;
				//确定要更新的属性名
				const property = this.tabsSide[this.tabsSideIndex] == '套餐' ? 'comboList' : 'dishList';
				let r = dictDataList[mealsKey][property]
				// 更新数据
				if (r.length > 0) {
					this.packageList = dictDataList[mealsKey][property]
				} else {
					uni.showLoading({ title: '请稍后...' });
					
					let res;
					if(this.weekNewType == 2){
						 res = await getDishListAPI2({
							...d,
							weyDate: this.weekObj.fullDate
						})
					}else{
						 res = await getDishListAPI({
							...d,
							weyDate: this.weekObj.fullDate
						})
					}
					
					if(res.code == 200){
						console.log(res.data)
						uni.hideLoading();
						this.packageList = this.addIdsToItems(res.data)
						dictDataList[mealsKey][property] = this.packageList;
						this.persistenceShoppingBag()
					}
					
					// this.getComboList(d)
				}
				//*********************这段代码为了解决，切换tab偶尔数据消失的问题******************************
				// if(this.tabsSideIndex==0){
				// 	const obj = this.tabsList[this.tabsCurrent]
				// 	let d = {
				// 		date: this.foodDateType[this.weekIndex].weekDay,
				// 		type: obj.id,
				// 	}
				// 	this.getComboList(d)
				// }else{
				// 	const obj = this.tabsList[this.tabsCurrent]
				// 	let d = {
				// 		date: this.foodDateType[this.weekIndex].weekDay,
				// 		type: obj.id,
				// 	}
				// 	// this.getDishList(d)
				// }
				// ***********************这段代码为了解决，切换tab偶尔数据消失的问题****************************
			},
			// 存储数据

			async getfoodSetMeal() {
				let res;
				if(this.weekNewType == 2){
					res = await getfoodSetMealAPI2()
				}else{
					res = await getfoodSetMealAPI()
				}
				this.shoppingData = res.data

				let d = this.shoppingData[this.weekIndex].dictDataList;
				// console.log('meals1');
				// console.log(d.meals2);
				// if (d.meals1) {
				// 	this.tabsCurrent = 0
				// } else if (d.meals2) {
				// 	this.tabsCurrent = 1
				// }
				if (this.paramsDate.dates) {
					uni.showLoading({
						title: '请稍后...'
					});


					// setTimeout(async ()=>{
					const data = await getRangeCopyAPI({
						beginTime: JSON.parse(this.paramsDate.dates).beginTime,
						endTime: JSON.parse(this.paramsDate.dates).endTime
					})
					data.data.mealsOfDays.forEach(ement => {
						this.shoppingData.forEach(el => {
							if (el.fullDate == this.getNextWeekSameDay(ement.originalDate)) {
								el.dictDataList = ement.dictDataList
							}
						})
					})
					this.persistenceShoppingBag()
					// this.packageList = data.data.mealsOfDays

					uni.hideLoading();
					// },1000)


				}
				this.setTabsList(res.data)
				this.tabsClick({
					index: 0
				})




			},
			undateShoppingData() {
				this.shoppingData = this.shoppingBagData // vuex获取
				// this.packageData = this.shoppingData[this.weekIndex].dictDataList
				this.tabsClick({
					index: this.tabsCurrent
				})
			},
			getShoppingData() {
				if (this.shoppingData.length == 0) {
					this.getfoodDateType()
				} else {
					this.shoppingData = this.shoppingBagData // vuex获取
					this.tabsClick({
						index: this.tabsCurrent
					})
				}
				this.$store.state.user.type = 0;
			},
			handleUpdateNum(item, e) {
				let target

				if (item.comboId) {
					target = this.packageList.find(i => i.comboId === item.comboId)
					if (target) target.saleNum = e
				} else if (item.foodId) {
					target = this.packageList.find(i => i.foodId === item.foodId)
					if (target) target.saleNum = e
				}

				this.persistenceShoppingBag()
			},
			persistenceShoppingBag() {
				const updatedData = JSON.parse(JSON.stringify(this.shoppingData))
				// updatedData[this.weekIndex].dictDataList = this.packageData
				this.$store.commit('SET_SHOPPINGBAGDATA', updatedData)
				// console.log(this.filterContentDataByNum());
			},

			hhhh() {},

		}
	}
</script>

<style scoped lang="scss">
	.page {
		position: relative;
		// height: 100vh;
		background: #F2F2F2;
		padding-bottom: 30rpx;

		.top_img {
			display: flex;
			flex-direction: column;
			// justify-content: space-between;
			// padding: 180rpx 40rpx 120rpx;
			padding-top: 120rpx;
			align-items: center;
			width: 100%;
			height: 350rpx;
			background-image: url('https://beihai-food.oss-cn-beijing.aliyuncs.com/03.png');
			// background-size: contain;
			background-size: cover;
			background-repeat: no-repeat;
			font-size: 36rpx;
			font-weight: 500;

			.text {
				font-size: 20rpx;
				color: #fff;
			}
		}

	}

	.content {
		position: relative;
		top: -130rpx;
		padding: 40rpx 20rpx 0;

		.login-btn {
			width: 150rpx;
			height: 44rpx;
			font-size: 28rpx;
			padding: 0;
			border: none;
		}


		.tabs {
			position: relative;
			left: -20rpx;
			// padding-left: 20rpx;
			// margin: 16rpx 0;
			margin-top: 16rpx;
			width: 100vw;
			// height: 80rpx;
			background: #fff;
			z-index: 2;
		}

		.tabsSide {
			position: relative;
			left: -20rpx;
			background-color: #fff;
			width: 120rpx;
			height: calc(100vh - 600rpx);

			.t {
				text-align: center;
				width: 100%;
				height: 100rpx;
				line-height: 100rpx;
			}

			.t_active {
				position: relative;
				color: #0EB275;
				background-color: #E6F7F1;
			}

			.t_active::after {
				content: "";
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				background: #0EB275;
				z-index: 9;
				width: 60rpx;
				height: 4rpx;
				border-radius: 0px 2px 2px 0px;
				/* 主色 */
				background: #0EB275;
			}
		}

		.meal_main {
			// padding-bottom: 120rpx;
			display: grid;
			grid-template-columns: auto 1fr;
			height: calc(100vh - 760rpx);

			.right_side {
				padding-top: 16rpx;
				padding-bottom: 200rpx;
				height: calc(100vh - 760rpx);
				overflow-y: auto;
			}
		}

		::v-deep .u-tabs__wrapper__nav__item__text {
			font-size: 28rpx;
		}

		::v-deep .u-tabs__wrapper__nav__item {
			width: 160rpx;
		}
	}
</style>